<template>
  <div class="search-result">
    <!-- 头部导航 -->
    <header class="header">
      <div class="container">
        <div class="header-content">
          <div class="logo" @click="goHome">
            <h1>新闻平台</h1>
          </div>
          <div class="search">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索新闻..."
              class="search-input"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
        </div>
      </div>
    </header>

    <!-- 搜索结果 -->
    <main class="main">
      <div class="container">
        <div class="search-info">
          <h2>搜索结果</h2>
          <p v-if="!loading">
            关键词"<strong>{{ currentKeyword }}</strong>"共找到 {{ total }} 条结果
          </p>
        </div>

        <div v-loading="loading" class="results">
          <div v-if="newsList.length > 0" class="news-list">
            <article 
              v-for="news in newsList" 
              :key="news.id" 
              class="news-item"
              @click="goToDetail(news.id)"
            >
              <div class="news-image" v-if="news.coverImage">
                <img :src="news.coverImage" :alt="news.title" />
              </div>
              
              <div class="news-content">
                <h3 class="news-title">{{ news.title }}</h3>
                <p class="news-summary">{{ news.summary }}</p>
                
                <div class="news-meta">
                  <span class="publish-time">{{ formatTime(news.publishTime) }}</span>
                  <div class="news-stats">
                    <span class="views">
                      <el-icon><View /></el-icon>
                      {{ news.viewCount }}
                    </span>
                    <span class="likes">
                      <el-icon><Star /></el-icon>
                      {{ news.likeCount }}
                    </span>
                  </div>
                </div>
              </div>
            </article>
          </div>
          
          <!-- 空状态 -->
          <div v-else-if="!loading" class="empty-state">
            <el-empty description="没有找到相关新闻">
              <el-button type="primary" @click="goHome">返回首页</el-button>
            </el-empty>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getNewsList } from '@/api/news'
import { View, Star, Search } from '@element-plus/icons-vue'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const newsList = ref([])
const searchKeyword = ref('')
const currentKeyword = ref('')

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 计算属性
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 方法
const fetchSearchResults = async () => {
  const keyword = route.query.keyword
  if (!keyword) {
    router.push('/')
    return
  }

  loading.value = true
  currentKeyword.value = keyword
  searchKeyword.value = keyword

  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: keyword
    }
    
    const data = await getNewsList(params)
    newsList.value = data.results || []
    total.value = data.count || 0
  } catch (error) {
    console.error('搜索失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  if (!searchKeyword.value.trim()) return
  
  router.push({
    name: 'SearchResult',
    query: { keyword: searchKeyword.value }
  })
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchSearchResults()
}

const goHome = () => {
  router.push('/')
}

const goToDetail = (id) => {
  router.push({ name: 'NewsDetail', params: { id } })
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
  
  return date.toLocaleDateString()
}

// 监听路由变化
watch(() => route.query.keyword, () => {
  currentPage.value = 1
  fetchSearchResults()
})

// 生命周期
onMounted(() => {
  fetchSearchResults()
})
</script>

<style scoped>
.search-result {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 头部样式 */
.header {
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.logo {
  cursor: pointer;
}

.logo h1 {
  color: #409eff;
  font-size: 20px;
  margin: 0;
}

.search-input {
  width: 400px;
}

/* 主要内容 */
.main {
  padding: 30px 0;
}

.search-info {
  margin-bottom: 30px;
}

.search-info h2 {
  color: #303133;
  font-size: 24px;
  margin: 0 0 10px 0;
}

.search-info p {
  color: #606266;
  margin: 0;
}

.search-info strong {
  color: #409eff;
}

/* 新闻列表 */
.news-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.news-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  gap: 20px;
}

.news-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}

.news-image {
  width: 150px;
  height: 100px;
  flex-shrink: 0;
  overflow: hidden;
  border-radius: 4px;
}

.news-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.news-content {
  flex: 1;
}

.news-title {
  font-size: 18px;
  color: #303133;
  margin: 0 0 10px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-summary {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin: 0 0 15px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.news-stats {
  display: flex;
  gap: 15px;
}

.news-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 空状态 */
.empty-state {
  background: white;
  border-radius: 8px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 15px 0;
    gap: 15px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .news-item {
    flex-direction: column;
    gap: 15px;
  }
  
  .news-image {
    width: 100%;
    height: 150px;
  }
}
</style>
